package com.egao.common.module.system.controller;

import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.system.entity.Dict;
import com.egao.common.module.system.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.beetl.ext.fn.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 字典管理
 * @author pyx
 */
@Api(tags = "字典管理")
@RestController
@RequestMapping("${api}")
public class DictController extends BaseController {

    @Autowired
    private DictService dictService;

    @PreAuthorize("hasAuthority('sys:dict:list')")
    @ApiOperation("分页查询字典")
    @ApiPageParam
    @GetMapping("/sys/dict/page")
    public PageResult<Dict> page(HttpServletRequest request) {
        PageParam<Dict> pageParam = new PageParam<>(request);
        return new PageResult<>(dictService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('sys:dict:list')")
    @ApiOperation("字典类型查询")
    @GetMapping("/sys/dict/types")
    public JsonResult types() {
        return JsonResult.ok().setData(dictService.listType());
    }

    @PreAuthorize("hasAuthority('sys:dict:insert')")
    @OperLog(value = "字典管理", desc = "添加", param = false, result = true)
    @ApiOperation("添加字典")
    @PostMapping("/sys/dict/insert")
    public JsonResult insert(@Valid @RequestBody Dict dict){
        return dictService.insertDict(dict);
    }

    @PreAuthorize("hasAuthority('sys:dict:update')")
    @OperLog(value = "字典管理", desc = "修改", param = false, result = true)
    @ApiOperation("修改字典")
    @PutMapping("/sys/dict/update")
    public JsonResult update(@Valid @RequestBody Dict dict){
        return dictService.updateDict(dict);
    }

    @PreAuthorize("hasAuthority('sys:dict:delete')")
    @OperLog(value = "字典管理", desc = "删除", param = false, result = true)
    @ApiOperation("删除字典")
    @DeleteMapping("/sys/dict/delete")
    public JsonResult delete(Integer id){
        return dictService.dictDelete(id);
    }

    @ApiOperation("查询字典集合根据字典类型")
    @GetMapping("/sys/dict/list")
    public JsonResult list(String type) {
        return JsonResult.ok().setData(dictService.cacheList(type));
    }

    @PreAuthorize("hasAuthority('sys:dict:list')")
    @ApiOperation("刷新缓存")
    @GetMapping("/sys/dict/reload-cache")
    public JsonResult reloadCache() {
        dictService.initRedis();
        dictService.saveCache();
        return JsonResult.ok();
    }
}
